package com.example.administrator.damaiwang.fragmentpack;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.example.administrator.damaiwang.R;
import com.example.administrator.damaiwang.adapter.YanChuAdapter;
import com.example.administrator.damaiwang.bean.AllContent;
import com.example.administrator.damaiwang.utils.HttpUtil;
import com.example.administrator.damaiwang.utils.LoadUrl;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class AllContentFragment extends Fragment {

   private static String A="http://mapi.damai.cn/ProjLst.aspx?source=10101&cc=0&ps=20&mc=";
   private static String B="&ot=0&v=0&appType=1&osType=2&p=";
    private  static int currentPager=1;
    private static final String C="&version=50609&channel_from=xiaomi_market&cityId=852";
    private  YanChuAdapter mAdapter;
    private  ListView mlv;
    private boolean isBottom;
    private  List<AllContent> list;
    private SwipeRefreshLayout refreshLayout;

    public static AllContentFragment createFragment(int index) {
        AllContentFragment fragment = new AllContentFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("which", index);
        fragment.setArguments(bundle);
        return fragment;
    }

     class MyHandle extends Handler{
        WeakReference<Fragment> reference;
        public MyHandle(Fragment fragment){
            reference=  new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Fragment fragment = reference.get();
            if (fragment!=null){
                switch (msg.what){
                    case HttpUtil.TEXT_TYPE:
                      String json= (String) msg.obj;

                        Log.e("===============",json);
                        //解析json
                        List<AllContent> contents = parseJson(json);
                        mAdapter.setData(contents);
                        refreshLayout.setRefreshing(false);
                        break;
                }
            }
        }

    }
    private  List<AllContent> parseJson(String json) {

        list = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONObject(json).getJSONArray("l");
            list.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                String name = object.getString("n");
                String time = object.getString("t");
                String price = object.getString("priceName");
                String VenName = object.getString("VenName");
                String imageId=String.valueOf(object.getInt("i"));
                AllContent content = new AllContent(name, price, time, VenName, imageId);
                list.add(content);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_all_content, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mlv = (ListView) view.findViewById(R.id.lv_allcontent);
        MyHandle myHandle = new MyHandle(this);
        final HttpUtil mUtil = new HttpUtil(myHandle);
        Bundle arguments = getArguments();
        final int position = arguments.getInt("which");
        mUtil.loadData(getUrl()[position],HttpUtil.TEXT_TYPE);
        mAdapter = new YanChuAdapter();
        mlv.setAdapter(mAdapter);

        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swip);


        refreshLayout.setColorSchemeColors(
                getResources().getColor(R.color.likered),
                getResources().getColor(R.color.green),
                getResources().getColor(R.color.blue)
        );

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPager=1;
                StringBuilder builder = new StringBuilder();
                builder.append(A).append(position).append(B).append(currentPager).append(C);
                mUtil.loadData(builder.toString(),HttpUtil.TEXT_TYPE);

            }
        });
        mlv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState==SCROLL_STATE_IDLE &&isBottom){
                        currentPager++;
                        StringBuilder builder = new StringBuilder();
                        builder.append(A).append(position).append(B).append(currentPager).append(C);

                        Log.i("Tag++++++++++++++++",builder.toString());
                        mUtil.loadData(builder.toString(),HttpUtil.TEXT_TYPE);

                }
            }
            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                isBottom =(firstVisibleItem+visibleItemCount)==totalItemCount;
            }
        });
   }
    public static String[] getUrl(){

        return new String[]{LoadUrl.ALLCONTENT,LoadUrl.VOCALCONCERT,LoadUrl.CONCERT
        ,LoadUrl.DRAMAOPERA,LoadUrl.DANCINGBALLET,LoadUrl.QUYUANCARLO};
    }
}
